package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.pojo.Result;
import com.itheima.service.OrderInfoService;
import com.itheima.utils.PayUtils;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.UuidUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/orderInfo")
public class OrderInfoController {
    @Reference
    private OrderInfoService orderInfoService;

    @Autowired
    private JedisPool jedisPool;

   /** @RequestMapping("/sendToTelPhone.do")
    public Result sendToTelPhone(@RequestParam("telephone")String telephone){
        //调用工具类生成一个验证码
        Integer validateCode = ValidateCodeUtils.generateValidateCode(4);
        //将验证码通过手机号发送给用户
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,validateCode.toString());

            //将验证码保存到redis中,有效时间10分钟
            Jedis resource = jedisPool.getResource();
            //设置一个key，用来保存验证码
            String key = telephone+ RedisMessageConstant.SENDTYPE_ORDER;
            //存到redis中
            resource.setex(key,60*10,validateCode.toString());

            //释放资源
            resource.close();

            return new Result(false, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (ClientException e) {
            e.printStackTrace();
            //验证码发送失败
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }*/
    @RequestMapping("/sendToTelPhone.do")
    public Result sendToTelPhone(@RequestParam("telephone")String telephone){
        //调用工具类生成一个验证码
        Integer validateCode = ValidateCodeUtils.generateValidateCode(4);
        System.out.println("你的验证码是:"+validateCode);
        Jedis resource = jedisPool.getResource();

        if (telephone == null || validateCode == null) {
            //验证码发送失败
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }else{
        //设置一个key，用来保存验证码
        String key = telephone+ RedisMessageConstant.SENDTYPE_ORDER;
        //存到redis中
        //将验证码保存到redis中,有效时间90秒
        resource.setex(key,90,validateCode.toString());
        //释放资源
        resource.close();
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        }
    }

    @RequestMapping("/checkValidateCodeFromRedis.do")
    public Result checkValidateCodeFromRedis(@RequestParam("telephone")String telephone,@RequestParam("validateCode") String validateCode){
        //判断验证码,电话是否为空
        if (telephone == null || validateCode == null) {
            return new Result(false,"");
        }else{
            Jedis resource = jedisPool.getResource();
            String key = telephone+ RedisMessageConstant.SENDTYPE_ORDER;
            String code = resource.get(key);
            System.out.println("用户输入的validateCode是:"+validateCode);
            System.out.println("redis中的code是:"+code);
            //判断redis中的验证是否失效
            if (code == null){
                //表示验证码失效了
                return new Result(false,"");
            }else{
                //释放资源
                resource.close();
                //判断用户输入的验证码是否正确
                if (code.equals(validateCode)){
                    System.out.println("验证码输入成功");
                    return new Result(true,"");
                }else{
                    System.out.println("验证码输入失败");
                    return new Result(false,"");
                }
            }
        }
    }

    @RequestMapping("/addOrderInfo.do")
    public Result addOrderInfo(@RequestBody Map<String,Object> map){
        return orderInfoService.addOrderInfo(map);
    }


    @RequestMapping("/payNotify.do")
    public void payNotify(HttpServletRequest request, HttpServletResponse response){
        try {
            ServletInputStream in = request.getInputStream();
//            // 2.将xml转为java对象
            XmlMapper xmlMapper = new XmlMapper();
            Map param = xmlMapper.readValue(in, Map.class);
            orderInfoService.updateStatus(param);
            // 4.返回微信平台，接收成功..
            HashMap<String, String> result = new HashMap<>();
            result.put("return_code", "SUCCESS");
            result.put("return_msg", "OK");
            // 将map转为xml
            String xml = xmlMapper.writeValueAsString(result);
            response.setContentType("application/xml;charset=utf-8");
            response.getWriter().write(xml);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping("/findPayStatus.do")
    public Result findPayStatus(@RequestParam("id") int id){
        int status= orderInfoService.findPayStatus(id);
        if(status==0){
            return new Result(false,"未支付");
        }else {
            return new Result(true,"已支付");
        }

    }
    @RequestMapping("/makeCode.do")
    public Result makeCode(@RequestParam("price") Integer price,@RequestParam("id") String id){
        String orderId = UuidUtils.getUUID();
        orderInfoService.addOrderId(orderId,id);
        String codeUrl= PayUtils.createOrder(orderId, 1);
        return new Result(true,"",codeUrl);
    }

    @RequestMapping("/cancelOrder.do")
    public Result cancelOrder(@RequestParam("id") int id){

        try {
            orderInfoService.cancelOrder(id);
            return new Result(true,"支付时间超时，预约已取消");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"系统繁忙，请重试");
        }
    }

}
